﻿CREATE FUNCTION PaymentScheduleCurrentByPrincipalBalance(
	@LoanID int,
	@PrincipalBalance money
)RETURNS TABLE
RETURN(
SELECT     TOP (1) PaymentNumber, Mos, Date, ToInterest, ToPrinciple, RemainingPrinciple, FinanceCharge, MinBalanceToRoll, Days, Date_F, Payment, 
                      PaymentNumber + (RemainingPrinciple - @PrincipalBalance) / ToPrinciple AS PaymentNumberReal
FROM         dbo.PaymentScheduleByLoanID(@LoanID) AS PaymentScheduleByLoanID_1
ORDER BY ABS(RemainingPrinciple - @PrincipalBalance)
)
--DECLARE @B TABLE(Balance int)
--DECLARE @C int SET @C = 100
--WHILE @C > 0 BEGIN
--	INSERT INTO @B VALUES(5140-@C*3)
--	SET @C = @C - 1
--END


--SELECT PS.* FROM @B B
--CROSS APPLY PaymentScheduleCurrentByPrincipalBalance(1051216,B.Balance)PS

